package org.groupg.practice.collections;

import org.apache.commons.codec.digest.MurmurHash3;
import org.apache.commons.collections4.bloomfilter.BloomFilter;
import org.apache.commons.collections4.bloomfilter.EnhancedDoubleHasher;
import org.apache.commons.collections4.bloomfilter.Shape;
import org.apache.commons.collections4.bloomfilter.SimpleBloomFilter;
import org.apache.commons.lang3.SerializationUtils;

import java.io.Serializable;

public class BloomFiltersExample {

     /**
     * Populates a Bloom filter with the items.  Uses a shape that
     * expects 10K items max and a false positive rate of 0.01.
     * @param items The items to insert.
     * @return the Bloom filter populated with the items.
     */
    public static BloomFilter populate(Object[] items) {
        return populate(Shape.fromNP(10000, 0.01), items);
    }

    /**
     * Populates a Bloom filter with the items.
     * @param shape The shape of the Bloom filter.
     * @param items The items to insert.
     * @return the Bloom filter populated with the items.
     */
    public static BloomFilter populate(Shape shape, Object[] items) {
        BloomFilter collection = new SimpleBloomFilter(shape);
        for (Object o : items) {
            // this example serializes the entire object, actual implementation
            // may want to serialize specific properties into the hash.
            byte[] bytes = SerializationUtils.serialize((Serializable) o);
            long[] hash = MurmurHash3.hash128(bytes);
            collection.merge(new EnhancedDoubleHasher(hash[0], hash[1]));
        }
        // collection now contains all the items from the list of items
        return collection;
    }
}